// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// s [author] rhyme_lph
// y [email]  rhymelph@gmail.com
// R [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/dashboard_reimburse_entity.dart';
import 'package:finance_app/src/entities/expanse_item_value.dart';
import 'package:finance_app/src/entities/expense_detail_entity.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/views/reimburse_provider.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/chart/normal_circle_chart.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:finance_app/src/widgets/list_item/list_expandable_item.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/list_item/reimburse_item.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

class ReimburseView extends StatefulWidget {
  @override
  _ReimburseViewState createState() => _ReimburseViewState();
}

class _ReimburseViewState extends State<ReimburseView>
    with
        StatefulPresenter<ReimburseView, HrAndPayrollProvider,
            ReimburseProvider>,
        KeepAliveMixin {
  @override
  Widget buildWidget(BuildContext context) => ColoredBox(
        color: Colors.white,
        child: listBuilder<bool>(
            selector: (_, __) => __.hasUp,
            builder: (BuildContext context, bool value, Widget child) =>
                SmartRefresher(
                  controller: provider.refreshController,
                  onRefresh: provider.onRefresh,
                  onLoading: provider.onLoadMore,
                  enablePullUp: provider.hasUp,
                  child: ListView(
                    controller: provider.controller,
                    children: [
                      child,
                      AppSpaces.h20,
                      listBuilder<
                          Tuple3<String, List<ExpenseDetailEntity>,
                              ExpanseItemValue>>(
                        selector: (_, __) => Tuple3(
                            __.currentType,
                            List.from(__.dataList),
                            __.expanseMap[__.currentType]),
                        builder: (BuildContext context,
                            Tuple3<String, List<ExpenseDetailEntity>,
                                    ExpanseItemValue>
                                value,
                            Widget child) {
                          if (value.item1 == null) {
                            return Column(
                              children: provider.expanseMap.entries
                                  .map((e) => ListExpandableItem(
                                        controller: e.value.controller,
                                        titleSpans: [
                                          TextSpan(
                                              text:
                                                  provider.getGroupName(e.key)),
                                          if (e.key == 'pending')
                                            TextSpan(
                                                text:
                                                    '(${(e.value.allData?.length ?? 0) > 10 ? '10+' : e.value.allData?.length ?? 0})',
                                                style: TextStyle(
                                                  color: aceRedColor,
                                                ))
                                        ],
                                      ))
                                  .toList(),
                            );
                          } else {
                            List<Widget> children = [];
                            for (final e in value.item3.groupMap.entries) {
                              children.add(TransactionRecordTitleItem(
                                topPadding: getDp(14),
                                title: e.key,
                              ));
                              children.add(AppSpaces.grayH05);
                              children.addAll(
                                  e.value.map(buildItemWidget).toList());
                            }
                            if (children.isEmpty) {
                              children.add(Padding(
                                padding: EdgeInsets.only(top: getDp(30)),
                                child:
                                    super.buildEmptyWidget(provider, context),
                              ));
                            }
                            return ListExpandableItem(
                              controller: value.item3.controller,
                              titleSpans: [
                                TextSpan(
                                    text: provider.getGroupName(value.item1)),
                                if (value.item1 == 'pending')
                                  TextSpan(
                                      text:
                                          '(${value.item3.allData.length > 10 ? '10+' : value.item3.allData.length})',
                                      style: TextStyle(
                                        color: aceRedColor,
                                      ))
                              ],
                              content: Column(
                                children: children,
                              ),
                            );
                          }
                        },
                      ),
                    ],
                  ),
                ),
            child: Column(
              children: [
                if (Config.hasPermission(PermissionUtils.hrPayroll))
                  AppSpaces.h20,
                if (Config.hasPermission(PermissionUtils.hrPayroll))
                  ListHeaderItem(
                    title: S.current.last_30_days_overview,
                  ),
                if (Config.hasPermission(PermissionUtils.hrPayroll))
                  AppSpaces.h20,
                if (Config.hasPermission(PermissionUtils.hrPayroll))
                  listBuilder<DashboardReimburseEntity>(
                    selector: (_, __) => __.data,
                    builder: (BuildContext context,
                            DashboardReimburseEntity value, Widget child) =>
                        Padding(
                      padding: EdgeInsets.symmetric(horizontal: getDp(44)),
                      child: NormalCircleChart(
                        itemTitle: value.title,
                        itemList: value.chartData.map((e) => e.name).toList(),
                        valueList: value.chartData
                            .map((e) => e.value.toDouble())
                            .toList(),
                        currency: value.currencyCode,
                        total: value.total,
                      ),
                    ),
                  )
              ],
            )),
      );

  Widget buildItemWidget(ExpenseDetailEntity e) {
    return PressedOpacityButton(
      onPressed: () => provider.onNavDetail(e),
      child: ReimburseItem(
        title: e.items.map((e) => e.category?.name ?? '').join(','),
        name: e.paidBy,
        time: DateTimeUtils.formatDateTimeString(e.issuedAt),
        currency: e.currencyCode,
        amount: e.total.toDouble(),
        realStatus: e.status,
        status: e.isOverdue == 1 && e.status == 'open'
            ? "Overdue"
            : FormUtils.getStatus(
                TransactionTypeUtils.getTransactionTypeStatus('expense'),
                e.status,
                e.status == 'open' && e.employeeId == null ? 1 : 0),
        // e.status,1),
        // status: e.status == 'closed' || e.reimburseStatus == 'later'
        //     ? null
        //     : FormUtils.getStatus(ReimburseModel.expense, e.reimburseStatus, 0),
      ),
    );
  }
}
